package com.yfbao.horizon.schedule.tk.log;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class ZeroCopyWriter {
    private static FileChannel channel;
    private static final ByteBuffer buffer = ByteBuffer.allocateDirect(8192);

    public static void write(String message) throws IOException {
        byte[] bytes = message.getBytes(StandardCharsets.UTF_8);

        synchronized (buffer) {
            if (buffer.remaining() < bytes.length) {
                flush();
            }
            buffer.put(bytes);
        }
    }

    public static void flush() throws IOException {
        synchronized (buffer) {
            buffer.flip();
            getChannel().write(buffer);
            buffer.clear();
        }
    }

    private static FileChannel getChannel() throws IOException {
        if (channel == null || !channel.isOpen()) {
            channel = new RandomAccessFile("logs/frontend.log", "rw").getChannel();
        }
        return channel;
    }
}
